package com.xckj.cycling.view

import android.content.Context
import android.util.AttributeSet
import com.xckj.cycling.framework.lazyGlobalViewModel
import com.mapbox.navigation.base.trip.model.RouteProgress
import com.mapbox.navigation.base.trip.model.RouteProgressState
import com.mapbox.navigation.ui.maneuver.view.MapboxManeuverView
import com.mapbox.navigation.ui.shield.model.RouteShieldCallback
import com.xckj.cycling.viewmodel.NavigationToStartViewModel

class NavigationToStartMapView(context: Context, attrs: AttributeSet? = null) :
    RouteMapView(context, attrs) {
    private val viewModel: NavigationToStartViewModel by lazyGlobalViewModel()

    /**
     * The [RouteShieldCallback] will be invoked with an appropriate result for Api call
     * [MapboxManeuverApi.getRoadShields]
     */
    private val roadShieldCallback =
        RouteShieldCallback { shields -> maneuverView?.renderManeuverWith(shields) }
    var maneuverView: MapboxManeuverView? = null
    private var complete = false
    override fun maneuvers(routeProgress: RouteProgress) {
        maneuverView?.apply {
            val maneuvers = maneuverApi.getManeuvers(routeProgress)
            maneuvers.fold(
                { error ->
                },
                {
                    maneuvers.onValue { maneuverList ->
                        maneuverApi.getRoadShields(maneuverList, roadShieldCallback)
                    }
                    renderManeuvers(maneuvers)
                }
            )
        }
        if (routeProgress.currentState == RouteProgressState.COMPLETE) {
            if (complete) {
                return
            }
            complete = true
            viewModel.navigationEnd(true)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mapboxNavigation.stopTripSession()
    }

}